(function($) {
	var startBtn, endBtn, thisWeekBtn;
	var wardArray = []; //选择病区数据
	var docArray = []; //选择医生数据
	var sourceData = [];
	var currentHeight = window.screen.height;
	var currentWidth = window.screen.width;
	var userpicker;
	var perInfo
	mui.init({
		swipeBack: true, //启用右滑关闭功能
	});

	mui.plusReady(function() {
		plus.navigator.setStatusBarBackground('#24af96');
		plus.navigator.setStatusBarStyle('light');
		
		var _self = plus.webview.currentWebview();
		_self.setStyle({
			popGesture: 'none'  // 作用于ios 禁止右滑关闭
		});
		
		mui.back = function() {
			plus.navigator.setStatusBarBackground('#fff')
			plus.navigator.setStatusBarStyle('dark');
			_self.close("auto");
		}
		if (plus.os.name == 'iOS') {
			userpicker = new mui.xhPicker(1,'请选择','pickerId');
		}else{
			userpicker = new mui.PopPicker();
		}
		perInfo = app.getState()
		if(perInfo) {
			locId = perInfo.loginWardId //currentLoc['LocId'];
			locDesc = perInfo.loginWardDesc //currentLoc['LocDesc'];
		} else {
			mui.toast('用户未登录');
			plus.nativeUI.closeWaiting()
			var state = {};
			app.setState(state);
			localStorage.setItem('$user', JSON.stringify(state));
			plus.runtime.restart(); //重新启动
			return;
		}
		baseSetup();
		lastNextThisWeekBtnTap('T');
	});

	/*********   请求申请单列表 调用停诊申请API   *********************/
	function requestNurStopList() {
		plus.nativeUI.showWaiting('正在加载');
		//清空原来数据
		sourceData.splice(0, sourceData.length);
		wardArray.splice(1, wardArray.length);
		docArray.splice(1, docArray.length);
		var table = document.getElementById('table');
		mui('#table').off('tap','li',tableViewCellTapped) 
		table.innerHTML = '';
		mui('#scrollWrapper').scroll().scrollTo(0, 0, 100);
		var STDate = startBtn.getAttribute('data-value') //66919
		var EdDate = endBtn.getAttribute('data-value') //66950
		var pdict = {'useID':perInfo.hisUserID,depid:'',Type:'',STDate:STDate,EndDate:EdDate,
			NurAppFlag:'NURAPP'}
		var paramDict = {'method':'web.DHCStopASAuthExec:StopASApply',
			'params':JSON.stringify(pdict),'type':'Query'}
			// console.log(JSON.stringify(pdict))
		mui.DHCWebService(paramDict, function(result) {
		//postHttpRequest(xmlStr, 'nurse.stop.application', function(result) {
			// console.log(JSON.stringify(result))
			plus.nativeUI.closeWaiting();
			if (result.msgcode != '1') {
				mui.toast(result.msg)
				return;
			}
			updateUI(result.data);
		}, function(error) {
			mui.toast(error);
			plus.nativeUI.closeWaiting();
		});
	}

	function updateUI(resultArray) {
		//resultArray = [{"SASAId":"99","UseName":"刘巍","LocName":"内分泌科门诊","MarkDesc":"刘巍","RegType":"","OPType":"","StopReason":"","StopResult":"停诊","StopTimeRange":"","DateTimeStr":"2024-03-25,下午","SASAStatus":"待审核","SASAAddDate":"2024-03-25","SASAAddTime":"16:05:45","LocDr":"153","MarkDr":"1770","RegTypeDr":"","OPTypeDr":"","StopReasonDr":"","StopResultDr":"131||1","ResumeText":"","ConfirmInfo":"  ","ExecInfo":"  ","ERepDoc":"","ERepDocDr":"","SuppleASDate":"","SuppleTimeRangeDr":"","SuppleTimeRangeDesc":""}]
		if (resultArray == undefined) {
			mui('#table').off('tap','li',tableViewCellTapped) 
			mui('#table')[0].innerHTML = '<p class="noDataTip" style="color:red;">data字段为空</p>';
			return
		}
		if (typeof resultArray == 'string') {
			if (resultArray.substring(0,1) == '[') {
				resultArray = JSON.parse(resultArray)
			}else{
				mui('#table')[0].innerHTML = '<p class="noDataTip" style="color:red;">'+resultArray+'</p>';
				return
			}
		}
		var table = document.getElementById('table');
		if(resultArray.length == 0) {
			var html = '<p class="noDataTip">当前周暂无停诊申请</p>';
			table.innerHTML = html;
			return;
		}
		var htmls = ''
		for(var i = 0; i < resultArray.length; i++) {
			var oneData = resultArray[i];
			sourceData.push(oneData);
			var docId = oneData.UseName;
			var docName = oneData.UseName;
			var wardid = oneData.LocName;
			var wardDesc = oneData.LocName;
			var GhaoType = oneData.RegType;
			if (GhaoType != '') {
				GhaoType = '('+GhaoType+')'
			}
			var wardType = oneData.OPType;
			var yuyueNo = oneData.AppedNum||'';
			var guahaoNo = oneData.RegisterNum||'';
			var quhaoNo = oneData.AppedArriveNum||'';
			var stopDate = oneData.DateTimeStr //changeDateFormat(oneData.ASDate||'');
			var stopTime = oneData.StopTimeRange;
			var reason = oneData.StopReason;
			var applyDate = oneData.SASAAddDate;
			var applyTime = oneData.SASAAddTime;
			var state = oneData.SASAStatus;
			var stateFlag = oneData.RBASStopFlag;
			var dealType = oneData.StopResult;
			var style = ''
			if(stateFlag == '1') { ////操作后的已审核
				style = 'style="border:red 1px solid;color:red"'
			}else if (state == '已取消执行') {
				style = 'style="border:lightgray 1px solid;color:lightgray"'
			}
			var dealDesc = '';
			if (dealType == '替诊') {
				dealDesc = oneData['ERepDoc']||''
			}else if (dealType == '补诊') {
				dealDesc = oneData.SuppleASDate+' '+oneData.SuppleTimeRangeDesc
			}
			while(dealDesc.indexOf('+') >= 0) {
				dealDesc = dealDesc.replace('++', '&nbsp;');
				dealDesc = dealDesc.replace('+', '&nbsp;');
			}
			if(dealDesc != '') {
				dealDesc = '(' + dealDesc + ')';
			}
			var wardObj = {
				LocId: wardid,
				LocDesc: wardDesc
			};
			var doctorObj = {
				docId: docId,
				docName: docName
			};
			if(!isInArray(wardObj, wardArray)) {
				wardArray.push(wardObj);
			}
			if(!isInArray(doctorObj, docArray)) {
				docArray.push(doctorObj);
			}
			
			htmls += '<li id="li-'+i+'" class="mui-table-view-cell stoplist">'+
				'<div class="head"><div class="doctorName">' + docName  + GhaoType + '</div>'+
					'<div class="ward">' + wardDesc + '</div></div>'+
				'<div class="mui-card-content">'+
					'<div class="label">门诊类型：</div><div class="labelKey">' + wardType + '</div><br />'+
					'<div class="label">已预约数：</div><div class="labelKey">' + yuyueNo + '</div><br />'+
					'<div class="label">已挂号数：</div><div class="labelKey">' + guahaoNo + '</div><br />'+
					'<div class="label">已取号数：</div><div class="labelKey">' + quhaoNo + '</div><br />'+
					'<div class="label">停诊原因：</div><div class="labelKey">' + reason + '</div><br />'+
					'<div class="label">停诊处理：</div><div class="labelKey dealKey">' + dealType + 
					'<span class="labelKey dealDesc">' + dealDesc + '</span></div><br />'+
					'<div class="label">就诊单元：</div><div class="labelKey">' + stopDate + '&nbsp;' + stopTime + 
					'</div><div class="statetip" '+style+'>' + state + '</div>'+
					'<div class="applyDate">' + applyDate + '\/' + applyTime + '</div></div>'+
				'</li>'
		}
		table.innerHTML = htmls;
		mui('#table').on('tap','li',tableViewCellTapped) 
	}

	function isInArray(value, arr) {
		var flag = false;
		for(var i = 0; i < arr.length; i++) {
			var tempArr = arr[i];
			if(isObjectValueEqual(tempArr, value)) {
				flag = true;
			}
		}
		return flag;
	}

	function isObjectValueEqual(a, b) {
		//取对象a和b的属性名
		var aProps = Object.getOwnPropertyNames(a);
		var bProps = Object.getOwnPropertyNames(b);
		//判断属性名的length是否一致
		if(aProps.length != bProps.length) {
			return false;
		}
		//循环取出属性名，再判断属性值是否一致
		for(var i = 0; i < aProps.length; i++) {
			var propName = aProps[i];
			if(a[propName] !== b[propName]) {
				return false;
			}
		}
		return true;
	}

	//展示科室列表
	function showWardDocList(dataArr, keyStr, btnId, index) {
		if(dataArr.length != 0) {
			var pickerArr = [];
			for(var i = 0; i < dataArr.length; i++) {
				var oneData = dataArr[i];
				oneData.text = oneData[keyStr];
				oneData['index'] = i.toString();
				pickerArr[i] = oneData;
			}
			if (plus.os.name == 'iOS') {
				var ptitle = '选择科室'
				if (btnId == 'showDocs') {
					ptitle = '选择医生'
				}
				userpicker.setData(dataArr,ptitle);
				userpicker.setSelectIndex(index);
			}else{
				userpicker.setData(dataArr);
				userpicker.pickers[0].setSelectedIndex(index, 800);
			}
			
			userpicker.show(function(items) {
				var btn = document.getElementById(btnId);
				var item = btn.querySelector('.textContent');
				item.setAttribute('data-index', items[0]['index']);
				item.innerText = items[0].text;
				updateFilterUI();
			});
		}
	}

	function updateFilterUI() {
		var showWards = document.getElementById('showWards');
		var wardE = showWards.querySelector('.textContent');
		var showDocs = document.getElementById('showDocs');
		var docE = showDocs.querySelector('.textContent');
		var wardKey = '',
			wardValue = wardE.innerText;
		var docKey = '',
			docValue = docE.innerText;
		if(wardValue != '请选择' && wardValue.indexOf('全部') < 0) {
			wardKey = 'LocName';
		}
		if(docValue != '请选择' && docValue.indexOf('全部') < 0) {
			docKey = 'UseName';
		}

		var table = document.getElementById('table');
		mui('#scrollWrapper').scroll().scrollTo(0, 0, 100);
		var lis = table.querySelectorAll('.mui-table-view-cell');
		for(var i = 0; i < lis.length; i++) {
			var oneData = sourceData[i];
			var oneLi = lis[i];
			if(docKey == '') {
				if(wardKey != '' && oneData[wardKey] != wardValue) {
					oneLi.style.display = 'none';
				} else {
					oneLi.style.display = 'block';
				}
			} else {
				if(oneData[docKey] != docValue) {
					oneLi.style.display = 'none';
				} else if(wardKey != '' && oneData[wardKey] != wardValue) {
					oneLi.style.display = 'none';
				} else {
					oneLi.style.display = 'block';
				}
			}
		}
	}

	function baseSetup() {
		mui('.mui-scroll-wrapper').scroll({
			bounce: true,
			indicators: false, //是否显示滚动条
			deceleration: mui.os.ios ? 0.003 : 0.0009
		});
		startBtn = document.getElementById('starttime');
		endBtn = document.getElementById('endtime');
		thisWeekBtn = document.getElementById('thisWeekBtn');

		var showWards = document.getElementById('showWards');
		showWards.addEventListener('tap', function() {
			var contentE = this.querySelector('.textContent');
			var indexStr = contentE.getAttribute('data-index');
			showWardDocList(wardArray, 'LocDesc', 'showWards', parseInt(indexStr));
		});
		var showDocs = document.getElementById('showDocs');
		showDocs.addEventListener('tap', function() {
			var contentE = this.querySelector('.textContent');
			var indexStr = contentE.getAttribute('data-index');
			showWardDocList(docArray, 'docName', 'showDocs', parseInt(indexStr));
		});

		thisWeekBtn.addEventListener('tap', function() {
			lastNextThisWeekBtnTap('T');
		});
		var lastWeekBtn = document.getElementById('lastWeekBtn');
		lastWeekBtn.addEventListener('tap', function() {
			lastNextThisWeekBtnTap('L');
		});
		var nextWeekBtn = document.getElementById('nextWeekBtn');
		nextWeekBtn.addEventListener('tap', function() {
			lastNextThisWeekBtnTap('N');
		});
		var width = currentWidth * 0.75;
		var weekBtnWidth = (5 + 30 + 5) * 2 + 20;
		var timeWidth = (width - weekBtnWidth) / 2.0;
		startBtn.style.width = timeWidth + 'px';
		endBtn.style.width = timeWidth + 'px';
		
		var starttime = document.getElementById('starttime');
		var endtime = document.getElementById('endtime');
		if (plus.os.name == 'iOS') {
			starttime.addEventListener('tap', function() {
				iOSselectDatePicker('start');
			});
			endtime.addEventListener('tap', function() {
				iOSselectDatePicker('end');
			});
		} else{
			starttime.addEventListener('tap', function() {
				selectDatePicker('start');
			});
			endtime.addEventListener('tap', function() {
				selectDatePicker('end');
			});
		}
		//添加全部科室/病区数据
		var wardObj = {
			LocId: '',
			LocDesc: '全部科室'
		};
		wardArray.push(wardObj);
		var doctorObj = {
			docId: '',
			docName: '全部医生'
		};
		docArray.push(doctorObj);
		mui('#table').on('tap','li',tableViewCellTapped) 
	}
	
	function selectDatePicker(time) {
		var _self = this;
		if(_self.picker) {
			_self.picker.show(function(rs) {
				_self.innerText = rs.text;
				updateYearMonth(time,rs.text);
				_self.picker.dispose();
				_self.picker = null;
				
			});
		} else {
			_self.picker = new mui.DtPicker(
				{
					type: "date"
				}
			);
			_self.picker.show(function(rs) {
				_self.innerText = rs.text;
				updateYearMonth(time,rs.text);
				_self.picker.dispose();
				_self.picker = null;
			});
		}
	}
	function iOSselectDatePicker(time){
		var _self = this;
		plus.nativeUI.pickDate(function(e) {
			var d = e.date;
			var dateStr = d.getFullYear()+'-'
			if (d.getMonth() < 9) {
				dateStr += '0'
			}
			dateStr += (d.getMonth() + 1)+'-'
			if (d.getDate() < 10) {
				dateStr += '0'
			}
			dateStr += d.getDate()
			_self.innerText = dateStr;
			updateYearMonth(time,dateStr);
		}, function(e) {}, {});
	}
	
	function updateYearMonth(btn,dayStr){
		var starttime = document.getElementById('starttime');
		var endtime = document.getElementById('endtime');
		if(btn == 'start'){
			if(endtime.innerText >= dayStr){
				starttime.innerText = dayStr;
				getzdhDate().then(function(success){
					// console.log('aaa');
					requestNurStopList();
				},function(error){
					console.log('bbb');
				})
			}else{
				mui.toast('不得晚于' + endtime.innerText);
			}
			
		}else{
			if(dayStr >= starttime.innerText){
				endtime.innerText = dayStr;
				getzdhDate().then(function(success){
					console.log('aaa');
					requestNurStopList();
				},function(error){
					console.log('bbb');
				})
			}else{
				mui.toast('不得早于' + starttime.innerText);
			}
		}
	}
	
	function lastNextThisWeekBtnTap(weekStr) {
		var thisDay = initDays();
		if(weekStr == 'T') {
			var weekArr = thisWeek(thisDay);
			var lastWeekArr = lastWeek(thisDay);
			// console.log(JSON.stringify(weekArr))
			startBtn.innerText = lastWeekArr[0];
			// startBtn.innerText = weekArr[0];
			endBtn.innerText = weekArr[1];
		} else if(weekStr == 'L') {
			// var lastlastWeekArr = lastWeek(startBtn.innerText);
			endBtn.innerText = lastWeek(startBtn.innerText)[1];
			startBtn.innerText = lastWeek(endBtn.innerText)[0];
		} else if(weekStr == 'N') {
			// weekArr = nextWeek(startBtn.innerText);
			startBtn.innerText = nextWeek(endBtn.innerText)[0];
			endBtn.innerText = nextWeek(startBtn.innerText)[1];
		} else if(weekStr == 'R') { //刷新界面

		}
		var showWards = document.getElementById('showWards');
		var wardE = showWards.querySelector('.textContent');
		var showDocs = document.getElementById('showDocs');
		var docE = showDocs.querySelector('.textContent');
		wardE.innerText = '请选择';
		docE.innerText = '请选择';
		getzdhDate().then(function(success){
			requestNurStopList();
		},function(error){
			console.log('bbb');
		})
		
	}
	function getzdhDate(text){
		var count = 0
		var promise = new Promise (function(resolve, reject){
			var dict = {'inDate':startBtn.innerText}
			var paramDict = {'method':'web.INMOutInterface:zdhDate',
				'params':JSON.stringify(dict),'type':'Method'}
			mui.DHCWebService(paramDict, function(result) {
				startBtn.setAttribute('data-value',result.msg)
				count += 1
				if (count == 2) {
					resolve()
				}
			}, function(error) {
				count += 1
				if (count == 2) {
					reject()
				}
			});
			dict['inDate'] = endBtn.innerText
			paramDict['params'] = JSON.stringify(dict)
			mui.DHCWebService(paramDict, function(result) {
				endBtn.setAttribute('data-value',result.msg)
				count += 1
				if (count == 2) {
					resolve()
				}
			}, function(error) {
				count += 1
				if (count == 2) {
					resolve()
				}
			});
		})
		return promise
	}
	function tableViewCellTapped(){
		var indexStr = this.id.substr(3, this.id.length);
		var index = parseInt(indexStr);
		var liData = sourceData[index];
		var state = liData['SASAStatus'];
		if(state == '已取消执行') {
			mui.toast('已取消执行')
			return;
		}
		var sameIdArr = [];
		var sASAId = liData['ONCERequestID'];
		var sameIdIndex = 0;
		if(sASAId === '' || !sASAId){ // 改造过一次 改造前的数据 没有这个id 所以就单条停诊数据显示吧
			for(var i = 0; i < sourceData.length; i++) {
				var oneData = sourceData[i];
				if(liData['RBASId'] == oneData['RBASId']) {
					sameIdIndex = sameIdArr.length;
					sameIdArr.push(oneData);
				}
			}
		}else{
			for(var i = 0; i < sourceData.length; i++) {
				var oneData = sourceData[i];
				var oneSASAId = oneData['ONCERequestID'];
				if((oneSASAId != '') && (oneSASAId == sASAId)) {
					sameIdArr.push(oneData);
				}
			}
			sameIdArr = jsonSort(sameIdArr,'SASAId')
		}
		for(var i = 0; i < sameIdArr.length; i++) {
			if(liData['RBASId'] == sameIdArr[i]['RBASId']) {
				sameIdIndex = i
			}
		}
		var STDate = startBtn.getAttribute('data-value') //66919
		var EdDate = endBtn.getAttribute('data-value') //66950
		var pdict = {'useID':perInfo.hisUserID,depid:'',Type:'',STDate:STDate,EndDate:EdDate,
			NurAppFlag:'NURAPP'}
		var paramDict = {'method':'web.DHCStopASAuthExec:StopASApply',
			'params':JSON.stringify(pdict),'type':'Query'}
		// console.log(sameIdIndex)
		var objArg = {
				stopSourceArr: sameIdArr,
				stopData: liData,
				stopDataIndex: sameIdIndex,
				listXmlStr: paramDict
			};
		var detailPage = mui.openWindow({
			url: 'nurseStopDeal.html',
			id: 'nurseStopDeal',
			extras: objArg,
			waiting: {
				autoShow: false, //自动显示等待框，默认为true
			}
		});
		detailPage.addEventListener('close',function(){
			plus.nativeUI.closeWaiting()
			lastNextThisWeekBtnTap('R')
		})
	}
	
})(mui)

/*
 * [LOG] : [{'SASAId':'36','UseName':'王木','LocName':'KQKMZ-口腔科门诊','ASDate':'31/03/2019','StopTimeRange':'上午','SASAStatus':'已审核','RegType':'住院医师','OPType':'普通门诊','StopReason':'其他(测试)','SASAAddDate':'2019-03-28','SASAAddTime':'14:25:53','MarkDesc':'王木','StopResult':'替诊','RBASStopFlag':'0','ScheduleID':'26033||2623','stopResultTitle':'替诊医生'}]

stopResultTitle 替诊:替诊医生 补诊:补诊单元(补诊时间),

 * 数据格式
 * [{'SASAId':'36'			////----总Id
 * 'UseName':'王木',
 * 'LocName':'KQKMZ-口腔科门诊',
 * 'RegType':'住院医师',
 * 'OPType':'普通门诊',
 * 'ASDate':'31/03/2019','StopTimeRange':'上午',		////----停诊/替诊时间
 * 'SASAStatus':'已审核',	////----当前状态描述
 * 'RBASStopFlag':'0',		////----当前状态标识是否红色显示
 * 'StopReason':'其他(测试)',////----停诊原因
 * 'MarkDesc':'王木',
 * 'StopResult':'替诊(测试)',////----停诊处理()
 * 'SASAAddDate':'2019-03-28','SASAAddTime':'14:25:53',////----申请时间
 * 'ScheduleID':'26033||2623'/////--细分id
 * 
 * }]
 */